package GUI;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import modelo.Proveedores;
import proyectosge2b.TablaProveedores;
import persistencia.BaseDatosProveedor;


/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author DAM2B
 */
public class JPProveedorConsultar extends javax.swing.JPanel {

    ArrayList<Proveedores> datos;
    public static TablaProveedores mdtProveedores;
    public static String fila;
    public static String modificarProveedor;
    BaseDatosProveedor dbm;
    public static int IdProveedorSelect;
    public static String ProveedorFila = null;
    public static int CodProveedorSeleccionada;

    /**
     * Creates new form JPProveedorConsultar
     */
    public JPProveedorConsultar() throws SQLException, ClassNotFoundException {
        initComponents();

        dbm = new BaseDatosProveedor();
        datos = dbm.getProveedores();
        mdtProveedores = new TablaProveedores(datos);
        jTable1.setModel(mdtProveedores);

        ArrayList<String> proveedor = dbm.getListaCodigoProve();
        for (int i = 0; i < proveedor.size(); i++) {
            jComboBoxCodProv.addItem(proveedor.get(i));
        }

        jTextFieldNombrePro.setText("");

        jBmodificar.addActionListener(new ActionListener() {
            private TablaProveedores mdtProveedores;

            @Override
            public void actionPerformed(ActionEvent e) {

                String prueba = jTextFieldNombrePro.getText();
                Proveedores nProveedores = new Proveedores(prueba);
                if (jTextFieldNombrePro.getText().compareTo("") == 0 || jTextFieldNombrePro.getText().compareTo("") == 0) {
                    JOptionPane.showMessageDialog(null, "Selecciona una proveedor y escribe el nombre de la nuevo proveedor", "Informacion", JOptionPane.INFORMATION_MESSAGE);

                } else {
                    int codigo = JOptionPane.showConfirmDialog(null, "¿Seguro que quieres modificar esta proveedor?", "Información", JOptionPane.YES_NO_OPTION, JOptionPane.PLAIN_MESSAGE);
                    if (codigo == JOptionPane.YES_OPTION) {
                        System.out.println("Has pulsado en SI");
                        BaseDatosProveedor dbm = null;
                        try {
                            dbm = new BaseDatosProveedor();
                            dbm.updateProveedores(nProveedores, jTextFieldNombrePro.getText());
                            System.out.println("Proveedor MODIFICADO");
                            datos = dbm.getProveedores();
                            this.mdtProveedores = new TablaProveedores(datos);
                            jTable1.setModel(mdtProveedores);
                            jTextFieldNombrePro.setText("");
//                            jtfNombreMarca.setText("");
//                            jtfNuevaMarca.setText("");
                        } catch (ClassNotFoundException ex) {
                            System.err.println("DRIVER NO ENCONTRADO.");
                            ex.printStackTrace();
                        } catch (SQLException ex) {
                            System.err.println("SQLEXCEPTION.");
                            ex.printStackTrace();
                        } finally {
                            if (dbm != null) {
                                try {
                                    dbm.closeConnection();
                                } catch (SQLException exc) {
                                    System.err.println("SQLEXCEPTION DURANTE EL CIERRE.");
                                    exc.printStackTrace();
                                }
                            }
                        }
                    } else if (codigo == JOptionPane.NO_OPTION) {
                        System.out.println("Has pulsado en NO");
                    }
                }
            }
        });

        jComboBoxCodProv.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                String proveedorSeleccionada = jComboBoxCodProv.getSelectedItem().toString();
                BaseDatosProveedor dbm = null;
                try {
                    dbm = new BaseDatosProveedor();
                } catch (ClassNotFoundException ex) {
                    System.err.println(" Combobox marcas ClassNotFoundException");
                    Logger.getLogger(JPProveedorConsultar.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    System.err.println(" Combobox marcas SQLException");
                    Logger.getLogger(JPProveedorConsultar.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    IdProveedorSelect = dbm.getId(proveedorSeleccionada);
                } catch (Exception ex) {
                    System.err.println("Error conseguir id");
                    Logger.getLogger(JPProveedorConsultar.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        });
        
        
        jComboBoxCodProv.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {
                String ProveedorSeleccionado = jComboBoxCodProv.getSelectedItem().toString();
                BaseDatosProveedor dbm = null;
                try {
                    dbm = new BaseDatosProveedor();
                } catch (ClassNotFoundException ex) {
                    System.err.println("ClassNotFoundException comboboxmarca");
                    Logger.getLogger(JPProveedorConsultar.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    System.err.println("SQLException comboboxmarca");
                    Logger.getLogger(JPProveedorConsultar.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    CodProveedorSeleccionada = dbm.getCodProvedor(ProveedorSeleccionado);
                } catch (Exception ex) {
                    System.err.println("Error conseguir ID");
                    Logger.getLogger(JPProveedorConsultar.class.getName()).log(Level.SEVERE, null, ex);
                }

            }
        });
        jButtonBuscar.addActionListener(new ActionListener() {
            TablaProveedores mdtProveedores;

            @Override
            public void actionPerformed(ActionEvent e) {
                BaseDatosProveedor dbm = null;
                try {
                    dbm = new BaseDatosProveedor();
                } catch (ClassNotFoundException ex) {
                    System.err.println("Error INsertar en la tabla ClassNotFoundException ");
                    Logger.getLogger(JPProveedorConsultar.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    System.err.println("Error INsertar en la tabla SQLException ");
                    Logger.getLogger(JPProveedorConsultar.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    datos = dbm.getProveedores();
                } catch (SQLException ex) {
                    System.err.println("Error INsertar en la tabla SQLException ");
                    Logger.getLogger(JPProveedorConsultar.class.getName()).log(Level.SEVERE, null, ex);
                }
                try {
                    this.mdtProveedores = new TablaProveedores(datos);
                } catch (ClassNotFoundException ex) {
                    Logger.getLogger(JPProveedorConsultar.class.getName()).log(Level.SEVERE, null, ex);
                } catch (SQLException ex) {
                    Logger.getLogger(JPProveedorConsultar.class.getName()).log(Level.SEVERE, null, ex);
                }
                jTable1.setModel(mdtProveedores);
            }
        });

        //Actulizado 3/03/15
        jButtonBorrar.addActionListener(new ActionListener() {
            private TablaProveedores mdtProveedor;

            @Override
            public void actionPerformed(ActionEvent e) {
                Proveedores nProveedor = new Proveedores(fila);
                BaseDatosProveedor dbm = null;
                try {
                    Component componentePadre = null;
                    if (ProveedorFila != null) {
                        int confirmado = JOptionPane.showConfirmDialog(
                                componentePadre,
                                "¿Seguro que deseas borrar el proveedor?");

                        if (JOptionPane.OK_OPTION == confirmado) {
                            System.out.println("confirmado");
                            dbm = new BaseDatosProveedor();
                            dbm.deleteProveedores(nProveedor);
                            JOptionPane.showMessageDialog(null, "Cliente borrado correctamente", "¡BRAVO!", JOptionPane.INFORMATION_MESSAGE);
                            datos = dbm.getProveedores();
                            this.mdtProveedor = new TablaProveedores(datos);
                            jTable1.setModel(mdtProveedor);
                        } else {
                            System.out.println("vale... no borro nada...");
                        }
                    } else {
                        JOptionPane.showMessageDialog(componentePadre, "Selecciona un Proveedor", "Atención", JOptionPane.ERROR_MESSAGE);
                    }

                } catch (ClassNotFoundException ex) {
                    System.err.println("DRIVER NO ENCONTRADO.");
                    ex.printStackTrace();
                } catch (SQLException ex) {
                    System.err.println("SQLEXCEPTION.");
                    ex.printStackTrace();
                } finally {
                    if (dbm != null) {
                        try {
                            dbm.closeConnection();
                        } catch (SQLException exc) {
                            System.err.println("SQLEXCEPTION DURANTE EL CIERRE.");
                            exc.printStackTrace();
                        }
                    }
                }

            }
        });

        //Actulizado 3/03/15
        jTable1.addMouseListener(new MouseAdapter() {

            @Override
            public void mouseClicked(MouseEvent e
            ) {
                int row = jTable1.rowAtPoint(e.getPoint());
                fila = jTable1.getValueAt(row, 0).toString();
                // jTextFieldNombrePro.setText(fila);
                modificarProveedor = fila;
                ProveedorFila = "ok";
            }

        }
        );

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jToolBar1 = new javax.swing.JToolBar();
        jButtonBorrar = new javax.swing.JButton();
        jButtonConsultar = new javax.swing.JButton();
        jBmodificar = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jComboBoxCodProv = new javax.swing.JComboBox();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jTextFieldNombrePro = new javax.swing.JTextField();
        jButtonBuscar = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        setPreferredSize(new java.awt.Dimension(800, 600));

        jToolBar1.setRollover(true);

        jButtonBorrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fotos/Iconos/borrar.png"))); // NOI18N
        jToolBar1.add(jButtonBorrar);

        jButtonConsultar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fotos/Iconos/search.png"))); // NOI18N
        jToolBar1.add(jButtonConsultar);

        jBmodificar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/fotos/Iconos/modificar.png"))); // NOI18N
        jToolBar1.add(jBmodificar);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        jLabel1.setText("Consultar Proveedor");

        jComboBoxCodProv.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7" }));
        jComboBoxCodProv.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBoxCodProvActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jLabel3.setText("Nombre Proveedor");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel2.setText("Codigo Proveedor :");

        jButtonBuscar.setText("Buscar");

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {},
                {},
                {},
                {}
            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jToolBar1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(127, 127, 127)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(31, 31, 31)
                                .addComponent(jComboBoxCodProv, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(51, 51, 51)
                                .addComponent(jLabel3)
                                .addGap(18, 18, 18))
                            .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addComponent(jButtonBuscar)
                                    .addComponent(jLabel1))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)))
                        .addComponent(jTextFieldNombrePro, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(136, 136, 136)))
                .addGap(0, 27, Short.MAX_VALUE))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addContainerGap()
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 780, Short.MAX_VALUE)
                    .addContainerGap()))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jToolBar1, javax.swing.GroupLayout.PREFERRED_SIZE, 76, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(49, 49, 49)
                .addComponent(jLabel1)
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextFieldNombrePro, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2)
                    .addComponent(jComboBoxCodProv, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 36, Short.MAX_VALUE)
                .addComponent(jButtonBuscar)
                .addGap(340, 340, 340))
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(265, 265, 265)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 288, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(47, Short.MAX_VALUE)))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void jComboBoxCodProvActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBoxCodProvActionPerformed

    }//GEN-LAST:event_jComboBoxCodProvActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jBmodificar;
    private javax.swing.JButton jButtonBorrar;
    private javax.swing.JButton jButtonBuscar;
    private javax.swing.JButton jButtonConsultar;
    private javax.swing.JComboBox jComboBoxCodProv;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    public static javax.swing.JTextField jTextFieldNombrePro;
    private javax.swing.JToolBar jToolBar1;
    // End of variables declaration//GEN-END:variables
}
